package com.example.huajia.wx.db.dao;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.huajia.wx.db.pojo.CommentEntity;
import com.example.huajia.wx.db.pojo.DynamicEntity;
import com.mongodb.client.FindIterable;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Repository
public class DynamicDao {
    @Resource
    private MongoTemplate mongoTemplate;


    /**
     * 插入Dynamic
     */
    public String insert(DynamicEntity entity) {
        return mongoTemplate.save(entity, "dynamic").get_id();
    }

    /**
     * 更新Dynamic
     */
    public long update(String _id, Map<String, Object> change) {
        Query query = Query.query(Criteria.where("_id").is(_id));
        Update update = new Update();
        change.forEach(update::set);
        UpdateResult result = mongoTemplate.updateFirst(query, update, "dynamic");
        return result.getModifiedCount();
    }

    /**
     * 往集合中的_id对象下的listName列表中插入新的元素object
     */
    public long insertSubList(String _id, String listName, Object object) {
        Query query = Query.query(Criteria.where("_id").is(_id));
        Update update = new Update();
        update.push(listName).each(object);
        UpdateResult result = mongoTemplate.updateFirst(query, update, "dynamic");
        return result.getModifiedCount();
    }

    /**
     * 往集合中的_id对象下的listName列表中插入新的元素object
     */
    public long insertCommentSubList(String _id, String listName, String commentId, Object object) {
        Query query = Query.query(Criteria.where("_id").is(_id));
        query.addCriteria(Criteria.where("comment._id").is(commentId));
        Update update = new Update();
        update.addToSet("comment.$.like", object);
        UpdateResult result = mongoTemplate.updateFirst(query, update, "dynamic");
        return result.getModifiedCount();
    }

    /**
     * 往集合中的dynamicId对象下的listName列表中(逻辑)删除元素_id
     */
    public long deleteSubList(String dynamicId, String listName, Object object) {
        Query query = Query.query(Criteria.where("_id").is(dynamicId));
        Update update = new Update();
        update.pull(listName, object);
        UpdateResult result = mongoTemplate.updateFirst(query, update, "dynamic");
        return result.getModifiedCount();
    }

    /**
     * 往集合中的dynamicId对象下的listName列表中(逻辑)删除元素_id
     */
    public long deleteCommentSubList(String dynamicId, String listName, String commentId, Object object) {
        Query query = Query.query(Criteria.where("_id").is(dynamicId));
        query.addCriteria(Criteria.where("comment._id").is(commentId));
        Update update = new Update();
        update.pull("comment.$.like", object);
        UpdateResult result = mongoTemplate.updateFirst(query, update, "dynamic");
        return result.getModifiedCount();
    }

    /**
     * 查找Dynamic
     *
     * @param criteria 筛选条件
     */
    public List<DynamicEntity> search(Criteria criteria) {
        criteria.and("deleted").is(false);
        Query query = new Query(criteria).limit(88);
        query.with(Sort.by(
                Sort.Order.desc("createTime")
        ));
        List<DynamicEntity> ret = mongoTemplate.find(query, DynamicEntity.class, "dynamic");
        for (DynamicEntity dynamicEntity : ret){
            List<String> like = dynamicEntity.getLike();
            List<CommentEntity> comments = dynamicEntity.getComment();
            dynamicEntity.setLikeCount(like == null ? 0 : like.size());
            dynamicEntity.setCommentsCount(comments == null ? 0 : comments.size());
            dynamicEntity.setLike(like == null ? new ArrayList() : like);
        }
        return ret;
    }

    /**
     *
     */
    public DynamicEntity detail(String dynamicId) {
        DynamicEntity dynamic = mongoTemplate.findById(dynamicId, DynamicEntity.class);
        List<CommentEntity> list = getComments(dynamicId);
        dynamic.setComments(list);
        dynamic.setCommentsCount(list == null ? 0 : list.size());
        dynamic.setLikeCount(dynamic.getLike() == null ? 0 : dynamic.getLike().size());

        return dynamic;
    }

    /**
     * 获取动态下的所有评论
     */
    public List<CommentEntity> getComments(String dynamicId) {
        Query query = new Query();
        FindIterable iterable = mongoTemplate.getCollection("dynamic").find(query.getQueryObject()).sort(new Document("createTime", 1));
        Iterator iterator = iterable.iterator();
        while (iterator.hasNext()) {
            Document document = (Document) iterator.next();
            if (String.valueOf(document.get("_id")).equals(dynamicId)) {
                List list = document.get("comment", List.class);
                List<CommentEntity> ret = new ArrayList<>();
                if (list == null){
                    return ret;
                }
                for (int i = 0; i < list.size(); i++) {
                    String jsonStr = ((Document) list.get(i)).toJson();
                    CommentEntity comment = JSONObject.parseObject(jsonStr, CommentEntity.class);
                    ret.add(comment);
                }
                for (CommentEntity comment : ret){
                    List<CommentEntity> comments = comment.getComments();
                    List<String> like = comment.getLike();
                    comment.setCommentsCount(comments == null ? 0 : comments.size());
                    comment.setLikeCount(like == null ? 0 : like.size());
                    comment.setLike(like == null ? new ArrayList() : like);
                }
                Collections.sort(ret, new Comparator<CommentEntity>() {
                    @Override
                    public int compare(CommentEntity o1, CommentEntity o2) {
                        return o2.getCreateTime().compareTo(o1.getCreateTime());
                    }
                });

                return ret;
            }
        }
        return null;
    }



    public boolean updateComment(String _id, List<CommentEntity> list) {
        Query query = Query.query(Criteria.where("_id").is(_id));
        Update update = new Update();
        update.set("comment", list);
        mongoTemplate.updateFirst(query, update, "dynamic");
        return true;
    }

}
